package com.heima.comment.service.impl;

import com.heima.api.IArticleClient;
import com.heima.api.user.IUserClient;
import com.heima.comment.dtos.CommentDto;
import com.heima.comment.pojos.Comment;
import com.heima.comment.pojos.CommentLikes;
import com.heima.comment.service.ICommentRepayService;
import com.heima.comment.service.ICommentService;
import com.heima.comment.vos.CommentVo;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentServiceImpl implements ICommentService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private IUserClient userClient;
    @Autowired
    private CommentRepayServiceImpl commentRepayService;

    /**
     * 游客Id
     */
    private static final Integer VISITOR_ID = 0;

    /**
     * 评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult save(CommentDto dto) {
        if (VISITOR_ID.equals(AppThreadLocalUtil.getUser())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (ObjectUtils.isEmpty(dto.getArticleId()) || ObjectUtils.isEmpty(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApArticle article = articleClient.findArticleById(dto.getArticleId());
        if (ObjectUtils.isEmpty(article)) {
            log.info("文章不存在");
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (!commentRepayService.check(dto.getContent())) {
            return ResponseResult.errorResult(400, "评论内容包含敏感词");
        }
        Integer userId = AppThreadLocalUtil.getUser();
        ApUser userById = userClient.getUserById(userId);
        Comment comment = new Comment();
        comment.setContent(dto.getContent());
        comment.setEntryId(dto.getArticleId());
        comment.setCreatedTime(new Date());
        comment.setChannelId(article.getChannelId());
        comment.setLikes(0);
        comment.setType((short) 0);
        comment.setReply(0);
        comment.setAuthorId(userById.getId());
        comment.setAuthorName(userById.getName());
        comment.setImage(userById.getImage());
        mongoTemplate.save(comment);
        return ResponseResult.okResult(null);
    }

    /**
     * 评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(CommentDto dto) {
        if (StringUtils.isEmpty(dto.getArticleId()) || StringUtils.isEmpty(dto.getMinDate()) || StringUtils.isEmpty(dto.getIndex())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Date date = new Date(dto.getMinDate());
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("type").is(0)
                        .and("createdTime").lt(date))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        List<CommentVo> collect = comments.stream().map(comment -> {
            CommentVo commentVo = new CommentVo();
            BeanUtils.copyProperties(comment, commentVo);
            commentVo.setCreatedTime(comment.getCreatedTime().getTime());
            // 获取当前时间的Calendar实例
            Calendar calendar = Calendar.getInstance();

            // 减去24小时
            calendar.add(Calendar.HOUR_OF_DAY, -24);

            // 获取24小时前的Date对象
            Date oneDayAgo = calendar.getTime();
            List<CommentLikes> commentLikes = mongoTemplate.find(Query.query(Criteria.where("commentId").is(comment.getId())
                    .and("createdTime").gte(oneDayAgo)
                    .and("authorId").is(comment.getAuthorId())), CommentLikes.class);
            if (!CollectionUtils.isEmpty(commentLikes)) {
                commentVo.setOperation((short) 0);
            }
            return commentVo;
        }).collect(Collectors.toList());
        return ResponseResult.okResult(collect);
    }

    /**
     * 点赞，取消点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentDto dto) {
        Integer userId = AppThreadLocalUtil.getUser();
        if (VISITOR_ID.equals(userId)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (StringUtils.isEmpty(dto.getCommentId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getOperation() == 0) {
            //点赞
            CommentLikes commentLikes = new CommentLikes();
            commentLikes.setCommentId(dto.getCommentId());
            commentLikes.setAuthorId(userId);
            commentLikes.setCreatedTime(new Date());
            mongoTemplate.save(commentLikes);
            commentCount(dto.getCommentId(), 1);
        } else {
            //取消点赞
            mongoTemplate.remove(Query.query(Criteria.where("authorId").is(userId).and("commentId").is(dto.getCommentId())), CommentLikes.class);
            commentCount(dto.getCommentId(), 0);
        }
        return ResponseResult.okResult("SUCCESS");
    }

    /**
     * 加减点赞数量,0为减一，1为加一
     *
     * @param commentId
     */
    public void commentCount(String commentId, Integer operation) {
        Comment byId = mongoTemplate.findById(commentId, Comment.class);
        Update update = new Update().inc("likes", operation == 0 ? -1 : 1);
        mongoTemplate.updateFirst(Query.query(Criteria.where("id").is(commentId)), update, Comment.class);
    }
}
